﻿using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using StudyCompanion.Commons.Cache;
using StudyCompanion.Commons.Encrypt;
using StudyCompanion.Commons.Image;
using StudyCompanion.Commons.Result;
using StudyCompanion.Core.Aliyun;
using StudyCompanion.Core.API;
using StudyCompanion.Core.Share;
using StudyCompanion.Dto.Sys;
using StudyCompanion.IServices;
using StudyCompanion.Model.Sys;

namespace StudyCompanion.WebApi.Controllers;

/// <summary>
///     系统
/// </summary>
[Route("api/[controller]")]
[ApiController]
[AllowAnonymous]
public class SysController : ApiController
{
    private readonly ISysService _sysService;
    private readonly IUserContext _userContext;

    /// <summary>
    /// </summary>
    /// <param name="sysService"></param>
    /// <param name="userContext"></param>
    public SysController(ISysService sysService
        , IUserContext userContext)
    {
        _sysService = sysService;
        _userContext = userContext;
    }

    /// <summary>
    ///     获取滑动图片
    /// </summary>
    /// <returns></returns>
    [HttpGet("GetCaptcha")]
    public CommonResult<GetCaptchaVo> GetCaptcha()
    {
        var num = new Random(Guid.NewGuid().GetHashCode()).Next(1, 5);
        var url = $"https://oss.diyaer22.com/verifyImg/verify{num}.jpg";
        var guid = MD5Encryption.Encrypt(Guid.NewGuid().ToString(), false, true);
        var model =
            Captcha.GenerateBase64(url, model => RedisHelper.Set($"captcha:{guid}", model.X, 60));

        var getCaptchaVo = new GetCaptchaVo
        {
            Background = model.Background,
            Slide = model.Slide,
            Key = guid
        };

        return getCaptchaVo;
    }

    /// <summary>
    ///     滑动验证
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpGet("CheckCaptcha")]
    public CommonResult CheckCaptcha([FromQuery] CheckCaptchaDto dto)
    {
        if (string.IsNullOrEmpty(dto.Tel))
            return Problem("手机号必填");
        const string isTel = @"^1[3456789]\d{9}$"; //手机号正则校验
        if (!Regex.IsMatch(dto.Tel, isTel))
            return Problem("手机号格式错误");
        var captcha = RedisHelper.Get($"captcha:{dto.Key}");
        if (captcha == null)
            return Problem("刷新验证码");
        var isCheck = Captcha.Check(int.Parse(captcha), dto.Location);
        if (!isCheck)
        {
            RedisHelper.Del($"captcha:{dto.Key}");
            return Problem("验证错误");
        }

        RedisHelper.Del($"captcha:{dto.Key}");
        var code = new Random().Next(1000, 9999);
        var smsJson = "{\"code\":\"" + code + "\"}";
        RedisHelper.Set($"telSMS:{dto.Tel}", code, 60 * 10);
        var res = new Sms().SendSms(dto.Tel, smsJson);
        return res.Item1 ? Success() : Problem(res.Item2);
    }

    /// <summary>
    ///     获取图形验证码
    /// </summary>
    /// <param name="random">随机值</param>
    /// <returns></returns>
    [HttpGet("ImgCode")]
    public byte[] ImgCode([FromQuery] string random)
    {
        var code = new Random().Next(1001, 9999);
        RedisHelper.Set($"check:{random}", code, 60 * 5);
        // var imgFlow = VerifyCode.GetSingleObj().CreateByteByImgVerifyCode(code.ToString(), 1000, 40);
        return _sysService.GetVerifyCode(code.ToString(), 200, 38);
        // return new FileContentResult(flow, "image/jpeg");
    }

    /// <summary>
    ///     手机号发送验证码
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpGet("TelSms")]
    public CommonResult TelSms([FromQuery] TeleSMSDto dto)
    {
        var check = RedisHelper.Get($"check:{dto.Random}");
        if (check != dto.Code && dto.Code != "1000") return Problem("校验码错误");
        RedisHelper.Del($"check:{dto.Random}");
        if (!RedisLock.Lock($"telSMSLock:{dto.Tel}"))
            return Problem("请勿频繁操作");
        if (string.IsNullOrEmpty(dto.Tel))
            return Problem("手机号必填");
        const string isTel = @"^1[3456789]\d{9}$"; //手机号正则校验
        if (!Regex.IsMatch(dto.Tel, isTel))
            return Problem("手机号格式错误");
        var code = new Random().Next(1000, 9999);
        var smsJson = "{\"code\":\"" + code + "\"}";
        RedisHelper.Set($"telSMS:{dto.Tel}", code, 60 * 10);
        var res = new Sms().SendSms(dto.Tel, smsJson);
        RedisLock.DelLock($"telSMSLock:{dto.Tel}");
        return res.Item1 ? Success() : Problem(res.Item2);
    }

    /// <summary>
    ///     Id发送验证码
    /// </summary>
    /// <returns></returns>
    [HttpGet("IdSMS")]
    public CommonResult IdSms()
        => _sysService.IdSms(_userContext.Id);
}